package com.ruoyi.dl.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.dl.domain.DlUser;
import com.ruoyi.dl.service.IDlUserService;
import com.ruoyi.dl.uitls.HttpUtil;
import com.ruoyi.dl.uitls.WXBizDataCrypt;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.*;

/**
 * 微信登陆相关Controller
 *
 * @author wangshouli
 * @date 2021-01-05
 */
@Controller
@RequestMapping("/wechat/dl/login")
@CrossOrigin(allowCredentials = "true")
public class WeChatLoginController extends BaseController {

    @Autowired
    private IDlUserService iDlUserService;

    // 小程序 AppID
    private static final String APP_ID = "wx77e7fe44842c7040";
    // 小程序 AppSecret
    private static final String APP_SECRET = "c33291aafccb43fdb346a1282ce114b4";

    /**
     * 小程序授权登录
     */
    @RequestMapping("/miniLogin")
    @ResponseBody
    public Map<String, Object> miniLogin(String code, String encryptedData, String iv) {
        Map<String, Object> map = new HashMap<>();
        DlUser dlUser;
        Integer userId = 0;
        String params = "appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String s = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSONObject.parseObject(s);

        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        String unionid = jsonObject.getString("unionid");
        String result = WXBizDataCrypt.decrypt1(encryptedData, session_key, iv);
        JSONObject json = JSONObject.parseObject(result);

        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            if (unionid != null) {
                map.put("unionid", unionid);
            } else {
                map.put("unionid", null);
            }
            map.put("session_key", session_key);
            map.put("openid", openid);
            map.put("avatarUrl", json.getString("avatarUrl"));
            map.put("sex", json.getInteger("gender"));
            map.put("msg", "success");
            if (openid != null) {
                dlUser = iDlUserService.selectDlUserByOpenId(openid);
                if (dlUser != null) {
                    map.put("userId", dlUser.getId());
                    map.put("nickName", dlUser.getWxName());
                    userId = dlUser.getId();
                } else {
                    DlUser dlUserInfo = new DlUser();
                    dlUserInfo.setOpenId(openid);
                    dlUserInfo.setWxName(json.getString("nickName"));
                    dlUserInfo.setDlLevel(0);
                    dlUserInfo.setBalance(new BigDecimal(0));
                    dlUserInfo.setFreeze(new BigDecimal(0));
                    dlUserInfo.setAvatar(json.getString("avatarUrl"));
                    iDlUserService.insertDlUser(dlUserInfo);
                    DlUser dlUserNew = iDlUserService.selectDlUserByOpenId(openid);
                    map.put("userId", dlUserNew.getId());
                    map.put("nickName", json.getString("nickName"));
                }
            }
            return map;
        }
        map.put("msg", "error");
        return map;
    }

    @RequestMapping("/getPhone")
    @ResponseBody
    @Transactional
    public Object getPhoneNumber(String encryptedData, String session_key, String iv, String openId) {
        // 被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.getDecoder().decode(session_key);
        // 偏移量
        byte[] ivByte = Base64.getDecoder().decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);

            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject json = JSONObject.parseObject(result);
                DlUser dlUser = iDlUserService.selectDlUserByOpenId(openId);
                System.out.println("dlUser" + dlUser);
                if (dlUser != null) {
                    dlUser.setPhone(json.getString("phoneNumber"));
                    iDlUserService.updateDlUser(dlUser);
                }
                return json;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/verifyPayPassword")
    @ResponseBody
    public Map<String,Object> verifyPayPassword(String userId, String payPassword){
        Map<String,Object> map=new HashMap<>();
        try {
            if (StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(payPassword)) {
                DlUser dlUser=iDlUserService.selectDlUserById(Integer.valueOf(userId));
                if(dlUser!=null){
                    if (payPassword.equals(dlUser.getZfPassward())) {
                        map.put("code",1);
                        map.put("msg","验证成功");
                    } else {
                        map.put("code",0);
                        map.put("msg","密码错误");
                    }
                }else {
                    map.put("code",0);
                    map.put("msg","系统异常");
                }
            } else {
                map.put("code",0);
                map.put("msg","请输入支付密码");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",0);
            map.put("msg","系统异常");
        }
        return map;
    }
}
